import Taro from '@tarojs/taro';
import {View, Canvas, Image} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {actionCreator} from "../../store/actions";
import {request, unite} from '../../utils/index';
import IssueModal from "../../components/issue-modal/issueModal";
import Success from "../../asset/images/success.png";
import './issue.scss';
import UnionidModal from "../../components/unionid-modal/unionidModal";
import PhoneModal from "../../components/phone-modal/phoneModal";

class Issue extends Taro.Component {
    config = {
        navigationBarTitleText: '发布',
        navigationBarBackgroundColor: '#ffffff'
    };

    state = {
        cWidth: 0, //canvas宽
        cHeight: 0, //canvas高
        powerStatus: 'Y', // N没有权限  Y有权限
        powerStatusScc: false, //true 开通成功
        modalStatus: false,
        modalStatus1: false,
        unionId: false,
        phoneId: false,
    };

    temp = {
        isLoading: false,  //防止多次上拉刷新加载
        num: 0, //上传张数
        packImg: [], //存储压缩图片容器
        tempFilePath: [], //上传（图片）
    };

    componentDidShow() {
        const {backPage, getbackPage} = this.props;
        const _this = this;
        const params = {
            url: '/momments/hasPermission',
            method: 'GET',
            data:{}
        };
        request(params).then(ret => {
            if (ret) {
                this.setState({
                    powerStatus: ret.data
                });
                if (ret.data == 'N') { //没有权限
                    unite.showToast('您暂无权限发布').then(() => {
                        // Taro.switchTab({
                        //     url: `/pages/home/home`
                        // })
                    })
                } else { //有权限
                    if (!backPage) {
                        getbackPage('1');
                        Taro.chooseImage({
                            count: 9, //上传张数为1
                            sizeType: ['original', 'compressed'],
                            sourceType: ['album'],
                            success: (res) => {
                                this.temp.tempFilePath = [];
                                this.temp.packImg = [];
                                this.temp.num = Number(res.tempFilePaths.length);

                                Taro.navigateTo({
                                    url: './issuePage/issuePage?imgData=' + res.tempFilePaths
                                });

                                // for(let i = 0;i<res.tempFilePaths.length;i++) {
                                //     //5242880
                                //     //判断证件大于7M时不执行
                                //     if(res.tempFiles[i].size > 7340032) {
                                //         unite.showTipModal(`第${i+1}张图片太大了`);
                                //         this.temp.num -= 1; //上传数量减1
                                //         if (res.tempFilePaths.length == 1) {
                                //             _this.upImg();
                                //         }
                                //         continue
                                //     }
                                //     Taro.getImageInfo({
                                //         src: res.tempFilePaths[i],
                                //         success: (data) => {
                                //             //判断证件大小小于宽度并且为上传手持身份证照时执行, 否则压缩证件
                                //             let widthHeight = unite.imgZoom(data.width, data.height); //利用canvas压缩图片
                                //             //----------绘制图形并取出图片路径--------------
                                //             this.temp.packImg.push({ //存储要压缩的图片
                                //                 widthHeight: widthHeight,
                                //                 url: res.tempFilePaths[i]
                                //             });
                                //             //当压缩图片数量等于数量时执行压缩
                                //             if (this.temp.num == this.temp.packImg.length) {
                                //                 //  图片长宽   图片路径  压缩张数索引值
                                //                 this.setCanvas(this.temp.packImg[0].widthHeight, this.temp.packImg[0].url, 0);
                                //             }
                                //             // this.setCanvas(widthHeight, res.tempFilePaths[i]);  //Taro.canvasToTempFilePath   Canvas 在子组件中存在bug，所以提到父组件压缩
                                //         }
                                //     })
                                // }
                            },
                            fail: () => {
                                Taro.switchTab({
                                    url: `/pages/home/home`
                                })
                            }
                        })
                    }
                }
            }
        });
    }

    upImg = () => {
        const _this = this;
        if(this.temp.isLoading) return;
        this.temp.isLoading = true;
        Taro.chooseImage({
            count: 9, //上传张数为1
            sizeType: ['original'],
            sourceType: ['album'],
            success: (res) => {
                this.temp.isLoading = false; //防止多次
                this.temp.tempFilePath = [];
                this.temp.packImg = [];
                this.temp.num = Number(res.tempFilePaths.length);
                //5242880
                for(let i = 0;i<res.tempFilePaths.length;i++) {
                    //5242880
                    //判断证件大于7M时不执行
                    if(res.tempFiles[i].size > 7340032) {
                        unite.showTipModal(`第${i+1}张图片太大了`);
                        this.temp.num -= 1; //上传数量减1
                        if (res.tempFilePaths.length == 1) {
                            _this.upImg();
                        }
                        continue
                    }
                    Taro.getImageInfo({
                        src: res.tempFilePaths[i],
                        success: (data) => {
                            //判断证件大小小于宽度并且为上传手持身份证照时执行, 否则压缩证件
                            let widthHeight = unite.imgZoom(data.width, data.height); //利用canvas压缩图片
                            //----------绘制图形并取出图片路径--------------
                            this.temp.packImg.push({ //存储要压缩的图片
                                widthHeight: widthHeight,
                                url: res.tempFilePaths[i]
                            });
                            //当压缩图片数量等于数量时执行压缩
                            if (this.temp.num == this.temp.packImg.length) {
                                //  图片长宽   图片路径  压缩张数索引值
                                this.setCanvas(this.temp.packImg[0].widthHeight, this.temp.packImg[0].url, 0);
                            }
                            // this.setCanvas(widthHeight, res.tempFilePaths[i]);  //Taro.canvasToTempFilePath   Canvas 在子组件中存在bug，所以提到父组件压缩
                        }
                    })
                }
            },
            fail: () => {
                Taro.switchTab({
                    url: `/pages/home/home`
                })
            }
        })
    };

    //压缩证件
    setCanvas = (widthHeight, value, ix) => {
        //  widthHeight图片长宽   value图片路径  ix压缩张数索引值
        const {cWidth, cHeight} = this.state;
        Taro.showLoading({
            title: '图片压缩中...' //加载框
        });
        let ctx = Taro.createCanvasContext('myCanvas', this.$scope);
        ctx.clearRect(0, 0, cWidth, cHeight); //清空画布
        this.setState({
            cWidth:widthHeight.canvasWidth, //赋值压缩后的宽度
            cHeight: widthHeight.canvasHeight //赋值压缩后的高度
        });
        ctx.drawImage(value, 0, 0, widthHeight.canvasWidth, widthHeight.canvasHeight);
        setTimeout(() => {
            ctx.draw(true, () => {
                console.log('zhao');
                Taro.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    destWidth: widthHeight.canvasWidth,
                    destHeight: widthHeight.canvasHeight,
                    quality: 0.2,
                    fileType:'jpg',
                    success: (datas) => {
                        console.log(JSON.stringify(datas.tempFilePath) + 'zhao');
                        this.temp.tempFilePath.push(datas.tempFilePath);
                        if (this.temp.tempFilePath.length == this.temp.num) {
                            Taro.hideLoading();
                            Taro.navigateTo({
                                url: './issuePage/issuePage?imgData=' + this.temp.tempFilePath
                            });
                        } else {
                            this.setCanvas(this.temp.packImg[ix+1].widthHeight, this.temp.packImg[ix+1].url, (ix+1));
                        }
                        // this.chkImg(datas.tempFilePath);
                        console.log(JSON.stringify(this.temp.tempFilePath) + 'this.temp.tempFilePath');
                        console.log(JSON.stringify(this.temp.num) + 'this.temp.num');
                    },
                    fail: () => {
                        unite.showTipModal(`第${ix+1}张图片上传失败`);
                        this.temp.num -= 1;
                        if (this.temp.tempFilePath.length == this.temp.num) {
                            Taro.hideLoading();
                            Taro.navigateTo({
                                url: './issuePage/issuePage?imgData=' + this.temp.tempFilePath
                            });
                        }
                    },
                    complete: (datas) => {
                        console.log(datas);
                    },
                })
            });   //留一定的时间绘制canvas
            // clearTimeout(clear);
        }, 1000);
    };

    tanchuanModel = () => {
        const {mobileFlag, existUser} = this.props;
        if (existUser == 0) { //未授权用户信息
            this.setState({
                unionId: true
            });
            return;
        }
        if (mobileFlag == 0) { //未授权手机号
            this.setState({
                phoneId: true
            });
            return;
        }
        this.setState((prevState)=>({
            modalStatus: !prevState.modalStatus,
        }));
    };

    tanchuanModel1 = () => {
        const {mobileFlag, existUser} = this.props;
        if (existUser == 0) { //未授权用户信息
            this.setState({
                unionId: true
            });
            return;
        }
        if (mobileFlag == 0) { //未授权手机号
            this.setState({
                phoneId: true
            });
            return;
        }
        this.setState((prevState)=>({
            modalStatus1: !prevState.modalStatus1,
        }));
    };

    confirmPhone = () => {
        const params = {
            url: '/invitation/apply/activate',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                this.setState((prevState)=>({
                    modalStatus: !prevState.modalStatus,
                }), () => {
                    this.tanchuanModel1();
                });
            }
        });
    };

    unGetUserInfo = (is) => {
        const {mobileFlag, setExistUser} = this.props;
        if (is) {
            setExistUser(1);
            this.setState({
                phoneId: mobileFlag == 0 ? true : false
            })
        }
        this.setState({
            unionId: false, //关闭 nu ni id 弹窗
        });
    };

    //授权手机号
    unGetPhone = (is) => {
        const {setMobileFlag} = this.props;
        if (is) {
            setMobileFlag(1);
        }
        this.setState({
            phoneId: false, //关闭弹窗
        });
    };

    confirm = (num) => {
        console.log(num);
        const params = {
            url: '/invitation/comments/activate',
            data:{
                momentsActivateCode: num,
            }
        };
        request(params).then(res => {
            if (res) {
                this.setState((prevState)=>({
                    modalStatus1: !prevState.modalStatus1,
                    powerStatusScc: true,
                }));
                unite.showToast(res.data)
            }
        });
    };

    returns = () => {
        Taro.switchTab({
            url: `/pages/home/home`
        })
    };

    render() {
        const {cWidth, cHeight, powerStatus, modalStatus, modalStatus1, powerStatusScc, unionId, phoneId} = this.state;
        return (
            <View className="page">
                {(powerStatus == 'N' && !powerStatusScc) &&(
                    <View className="power-wrap">
                        <View className="power-quan flex-center">sorry</View>
                        <View className="power-text">仅限教练</View>
                        <View className="power-title">每周限量开放特邀玩家。</View>
                        <View className="power-btn-wrap flex-lr">
                            <View className="btns flex-center" onClick={this.tanchuanModel1}>有邀请码</View>
                            <View className="btns btns-next flex-center" onClick={this.tanchuanModel}>获取特邀名额</View>
                        </View>
                    </View>
                )}
                {(powerStatus == 'N' && powerStatusScc) &&(
                    <View className="power-wrap">
                        <Image src={Success} className="power-quan flex-center"/>
                        <View className="power-text">太酷了，欢迎来到小动镜！</View>
                        <View className="power-title"></View>
                        <View className="power-btn-wrap flex-lr">
                            <View className="btns flex-center" onClick={this.returns}>返回</View>
                            <View className="btns btns-next flex-center" onClick={this.upImg}>发布</View>
                        </View>
                    </View>
                )}
                { modalStatus &&(
                    <IssueModal messageText='短信获取邀请码' onCancel={this.tanchuanModel} cancelText="下次再玩" onConfirm={this.confirmPhone} confirmText='GO获取'/>
                )}
                { modalStatus1 &&(
                    <IssueModal messageText='输入邀请码' onCancel={this.tanchuanModel1} inpSate={true} cancelText="下次再玩" onConfirm={this.confirm} confirmText='GO确认'/>
                )}
                {unionId &&(
                    <UnionidModal onCancel={this.unGetUserInfo}/>
                )}
                {phoneId &&(
                    <PhoneModal onCancel={this.unGetPhone}/>
                )}
                <Canvas canvasId="myCanvas" style={`width: ${cWidth}px; height: ${cHeight}px; position: absolute; left:-10000px; top:-10000px; z-index: -100`}/>
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {userToken, map, backPage, mobileFlag, existUser} = state;
    return {
        userToken,
        map,
        backPage,
        mobileFlag,
        existUser
    }
};

const mapDispatchToProps = {
    getbackPage: actionCreator.getbackPage,
    setExistUser: actionCreator.setExistUser,
    setMobileFlag: actionCreator.setMobileFlag,
};

export default connect(mapStateToProps, mapDispatchToProps)(Issue);
